package br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.admin.home.info;

import br.edu.ufcg.lsd.wbis.ui.client.beans.UserInfo;
import br.edu.ufcg.lsd.wbis.ui.client.ui.FormManager;
import br.edu.ufcg.lsd.wbis.ui.client.ui.management.InfoManager;

import com.gwtext.client.widgets.form.Form;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.TextField;
import com.gwtext.client.widgets.form.ValidationException;
import com.gwtext.client.widgets.form.Validator;
import com.gwtext.client.widgets.layout.AnchorLayoutData;

public class ChangePasswordPanel extends FormPanel implements FormManager<UserInfo> {

	private static String CURRENT_PASSWORD = "currentpswd";
	private static String NEW_PASSWORD = "newpswd";
	private static String RETYPE_NEW_PASSWORD = "retypenewpswd";

	public ChangePasswordPanel(InfoManager<UserInfo> infoManager) {

		this.setBaseCls("x-plain");
		this.setLabelWidth(100);
		this.setWidth(300);
		this.setHeight(100);

		final TextField currentPswdField = new TextField("Current Password", CURRENT_PASSWORD);
		currentPswdField.setPassword(true);
		currentPswdField.setMinLength(5);
		this.add(currentPswdField, new AnchorLayoutData("90%"));

		final TextField newPswdField = new TextField("New Password", NEW_PASSWORD);
		newPswdField.setPassword(true);
		newPswdField.setMinLength(5);
		this.add(newPswdField, new AnchorLayoutData("90%"));

		final TextField retypeNewPswdField = new TextField("Retype New Password", RETYPE_NEW_PASSWORD);
		retypeNewPswdField.setPassword(true);
		retypeNewPswdField.setMinLength(5);
		retypeNewPswdField.setInvalidText("Password does not match!");
		retypeNewPswdField.setValidator(new Validator() {

			public boolean validate(String value) throws ValidationException {
				return newPswdField.getValueAsString().equals(value);
			}
		});
		this.add(retypeNewPswdField, new AnchorLayoutData("90%"));

		currentPswdField.focus();
	}

	/**
	 * {@inheritDoc}
	 */
	public UserInfo parseForm() {
		Form form = this.getForm();
		UserInfo userInfo = new UserInfo();
		userInfo.setOldPassword(form.findField(CURRENT_PASSWORD).getValueAsString());
		userInfo.setPassword(form.findField(NEW_PASSWORD).getValueAsString());
		userInfo.setRetypedPassword(form.findField(RETYPE_NEW_PASSWORD).getValueAsString());
		return userInfo;
	}
}
